package com.dg11185.nearshop.activity.user;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.view.View;

import com.android.nearshop.R;
import com.baidu.location.BDLocation;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.shop.ShopFragment.ListState;
import com.dg11185.nearshop.app.MyApplication;
import com.dg11185.nearshop.baidumap.MyMapLocation;
import com.dg11185.nearshop.baidumap.MyMapLocation.MyBDLocationListener;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.entity.Area;
import com.dg11185.nearshop.net.entity.Industry;
import com.dg11185.nearshop.net.entity.MerchantItem;
import com.dg11185.nearshop.net.request.GetFavorListRequest;
import com.dg11185.nearshop.net.response.GetFavorListResponse;
import com.dg11185.nearshop.net.response.NetStatus;
import com.dg11185.nearshop.view.adapter.ShopMainAdapter;
import com.dg11185.nearshop.view.xlistview.XListView;
import com.dg11185.nearshop.view.xlistview.XListView.IXListViewListener;
import com.wlper.lib.view.loading.BaseLoadLayout.LoadStateHandler;
import com.wlper.lib.view.loading.LoadLayoutWithTweenAnim;

public class FavoriteShopActivity extends SubPageActivity implements IXListViewListener {

    private final static int PAGE_SIZE = 10;

    private int total = 0;

    private int pageNo = 1;

    private ListState listState = ListState.INIT;

    private XListView listView = null;

    private ShopMainAdapter listAdapter = null;

    private List<MerchantItem> listDatas = null;

    private GetFavorListRequest request = null;

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_favor);
        setSubPageTitle("我的关注商家");
        listView = (XListView) this.findViewById(R.id.user_favor_list);
        listDatas = new ArrayList<MerchantItem>();
        listAdapter = new ShopMainAdapter(this, listDatas);
        listView.setAdapter(listAdapter);
        listView.setPullRefreshEnable(false);
        listView.setXListViewListener(this);

        String userId = MyApplication.getUser().userId;
        request = new GetFavorListRequest(userId);
        initDBData();
        if(MyMapLocation.location!=null){
            listAdapter.setLocation(MyMapLocation.location);
        }else{
            initLocationData();
        }
        initListDatas();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
    }

    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    private OrmLiteHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(this, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    private void initDBData() {
        Dao<Industry, Integer> industryDao = getHelper().getIndustryDao();
        Dao<Area, Integer> areaDao = getHelper().getAreaDao();
        try {
            List<Industry> industries = industryDao.queryForAll();
            List<Area> areas = areaDao.queryForAll();
            Map<String, String> industryMap = new HashMap<String, String>();
            Map<String, String> areaMap = new HashMap<String, String>();

            for (Industry i : industries) {
                industryMap.put(i.name, i.industryId);
            }
            for (Area a : areas) {
                areaMap.put(a.name, a.areaNum);
            }

            listAdapter.setAreaMap(areaMap);
            listAdapter.setIndustryMap(industryMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void initLocationData() {

        MyMapLocation mapLocation = new MyMapLocation(this, new MyBDLocationListener() {
            
            @Override
            public void onReceiveLocation(BDLocation bDLocation) {
                listAdapter.setLocation(bDLocation);
                listAdapter.notifyDataSetChanged();}
        });
        mapLocation.start();
    }

    private void initListDatas() {
        final LoadLayoutWithTweenAnim loadingView = (LoadLayoutWithTweenAnim) this
                .findViewById(R.id.user_favor_loading);
        loadingView.setStateHandler(new LoadStateListener());
        if (listState == ListState.INIT) {
            loadingView.onLoading();
        }
        if (request != null) {
            request.getParams().remove("chshSign");
        }
        request.add("pageNumber", pageNo + "").add("pageSize", PAGE_SIZE + "").encryption();
        request.setActionListener(new GetFavorListRequest.ActionListener<GetFavorListResponse>() {

            @Override
            public void onSuccess(GetFavorListResponse result) {
                if (NetStatus.SUCCESS == result.status) {
                    total = Integer.parseInt(result.total);
                    if (total == 0) {
                        listView.setVisibility(View.INVISIBLE);
                        loadingView.onNoData();
                    } else {
                        listView.setVisibility(View.VISIBLE);
                        listView.stopLoadMore();
                        loadingView.onLoadSuccess();
                        total = Integer.parseInt(result.total);
                        listDatas.addAll(result.merchants);
                        listAdapter.notifyDataSetChanged();
                        if (pageNo * PAGE_SIZE >= total) {
                            listView.setPullLoadEnable(false);
                        } else {
                            listView.setPullLoadEnable(true);
                        }
                    }

                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                listView.stopLoadMore();
                loadingView.onLoadFailed();
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    loadingView.setLoadFailedHint("网络连接错误，连接之后点击重试!");
                } else if (resultCode == -1) {
                    loadingView.setLoadFailedHint("服务器连接失败!");
                }
            }
        });
        NetCacheClient.httpCacheGet(request);
    }

    @Override
    public void onRefresh() {
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        listState = ListState.LOAD_MORE;
        initListDatas();
    }

    private class LoadStateListener implements LoadStateHandler {

        @Override
        public void onLoading() {
        }

        @Override
        public void onLoadFailed() {
        }

        @Override
        public void onLoadSuccess() {
        }

        @Override
        public void onReload() {
            initListDatas();
        }

    }
}
